package _01_sort.leetcodeexerc.quicksort;

import org.junit.Test;

import java.util.Arrays;

import static _01_sort.SortUtil.swap;

/**
 * @author: mornd
 * @dateTime: 2023/6/24 - 11:17
 * 霍尔双边循环快排
 */
public class QuickSort2 {
    @Test
    public void test() {
//        int[] arr = {5, 2, 8, 1, 9, 3};
        int[] arr = {4,3,2,1};
        sort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    private void sort(int[] arr, int left, int right) {
        if (left < right) {
            int p = partition(arr, left, right);
            sort(arr, left, p - 1);
            sort(arr, p + 1, right);
        }
    }

    private int partition(int[] arr, int left, int right) {
        int pv = arr[left];
        int i = left;
        int j = right;
        while (i < j) {
            // 5,4,3,2,1
            while (arr[j] > pv) {
                j--;
            }
            while (i < j && arr[i] <= pv) {
                i++;
            }
            if (i != j) {
                swap(arr, i, j);
            }
        }
        swap(arr, i, left);
        return i;
    }
}
